using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Hosting;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace MvcWebRoleUpload.Models
{
    /// <summary>
    /// file system implementation
    /// </summary>
    public class LocalStorageHelper : IStorageHelper
    {

        private string _path;

        public LocalStorageHelper()
        {
            _path = RoleEnvironment.GetLocalResource("LocalStorageUpload").RootPath;

  
        }

        public List<ViewModelFile> GetAllPreviouslyUploadedFiles()
        {

            List<ViewModelFile> list = new List<ViewModelFile>();
             DirectoryInfo dirInfo = new DirectoryInfo(_path);
             FileInfo[] files = dirInfo.GetFiles();
            foreach (var item in files)
            {
                list.Add(new ViewModelFile() { Name = item.Name, Extension = item.Extension });
            }
            return list;

        }



        public ViewModelFile GetFileByName(string name)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(_path);
            FileInfo[] files = dirInfo.GetFiles();
            FileInfo file = files.SingleOrDefault(c => c.Name.ToUpperInvariant() == name.ToUpperInvariant());
            if (file != null)
            {
                return new ViewModelFile() { Name = file.Name, Extension = file.Extension , Path = file.FullName };
            }
            else
            {
                return null;
            }
        }


        public void Save(Stream stream , string fileName)
        {
            System.IO.FileInfo fi = new FileInfo(fileName);
            var path = Path.Combine(_path, fi.Name);

            if (stream.Length == 0) return;      
               using (FileStream fileStream = System.IO.File.Create(path, (int)stream.Length))     
               {         
                   byte[] bytesInStream = new byte[stream.Length];         
                   stream.Read(bytesInStream, 0, (int)bytesInStream.Length);          
                   fileStream.Write(bytesInStream, 0, bytesInStream.Length);      
               } 
        }
    }
}
